<?php
declare (strict_types=1);

namespace app;

use app\common\Consts;
use app\common\exception\ApiException;
use app\common\lists\ListsSearchTrait;
use app\models\user\AdminUserModel;
use app\models\user\UserModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\App;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use think\Validate;

/**
 * 控制器基础类
 */
abstract class BaseController
{

    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    protected $page;
    protected $limit;

    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;
        $this->page = $this->app->request->param('page') ?: 1;
        $this->limit = $this->app->request->param('limit') ?: 10;
    }

    /**
     * 成功返回
     * @param $data
     * @param string $message
     * @param int $code
     * @return \think\response\Json
     */
    protected function success($data = '', $message = 'success', $code = 200)
    {
        $result = [
            'code' => $code,
            'msg' => $message,
            'data' => $data
        ];
        return json()->data($result);
    }

    /**
     * 失败返回
     * @param array $data
     * @param \Exception|null $exception
     * @return \think\response\Json
     */
    protected function error($exception, $data = [])
    {
        $result = [
            'code' => $exception->getCode(),
            'msg' => $exception->getMessage(),
            'data' => $data
        ];
        if ($exception && !$exception instanceof ApiException && !$exception instanceof ValidateException) {
            Log::error(var_export($exception, true));
        }
        return json()->data($result);
    }

    /**
     * 下载
     * @param $spreadsheet
     * @param $filename
     * @param string $mode
     * @return string
     */
    protected function downloadExcel($spreadsheet, $filename, $mode = 'Xlsx')
    {
        $io_write = IOFactory::createWriter($spreadsheet, $mode);
        $routePath = public_path();
        $filePath = $filename . '.' . strtolower($mode);
        $path = $routePath . $filePath;
        $io_write->save($path);
        return $filePath;
    }

    /**
     * 删除文件
     *
     * @return bool
     */
    protected function removeFile()
    {
        if ($this->request->param('unlink_file_name')) {
            return unlink('../public/' . $this->request->param('unlink_file_name'));
        }
        return true;
    }
}
